﻿using OnCommon;
using OnLineLogFileComm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OnLineLogFileClient.Update
{
    public partial class Update : Form
    {
        public Update()
        {
            InitializeComponent();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (client != null)
                client.Dispose();
            base.OnClosing(e);
        }
        SocketTcpClient client;
        private void Update_Load(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                this.InvMsg("连接到服务器。。。");
                client = new SocketTcpClient();
                client.Connect("192.168.2.6", 20141);//服务器地址配置出去

                Command cmd = new Command();
                cmd.CommandType = OnLineLogFileComm.CommandType.CheckUpdateClientFiles;
                client.Send(cmd);
                var rData = client.Receive();
                var files = rData.GetObjData<List<string>>();

                var updatePath = Path.Combine(GetAssemblyPath(), "upadte_bin");
                if (!Directory.Exists(updatePath))
                    Directory.Delete(updatePath);
                Directory.CreateDirectory(updatePath);

                FileStream fs = null;
                int filesCount = 0;
                client.OnFileCompleted += (obj, hasCompleted) =>
                {
                    if (obj.HasFirst)
                    {
                        this.InvMsg("[" + obj.FileName + "] 开始下载。。。");

                        var filePath = Path.Combine(updatePath, obj.FileName);
                        this.InvMsg(String.Format("updatePath:{0},FileName:{1},filePath:{2}",
                            updatePath, obj.FileName, filePath));
                        fs = File.Create(filePath);
                    }
                    //this.InvMsg("[" + obj.FileName + "],CurrentBytes.Length:" + obj.CurrentBytes.Length
                    //    + ",CurrentFileLen:" + obj.CurrentFileLen);
                    try
                    {
                        fs.Write(obj.CurrentBytes, 0, obj.CurrentBytes.Length);
                    }
                    catch (Exception ex)
                    {
                        this.InvMsg(ex.Message);
                    }
                    if (hasCompleted)
                    {
                        this.InvMsg("[" + obj.FileName + "] 下载完成。" + fs.Name);

                        fs.Flush();
                        fs.Close();
                        fs.Dispose();
                        fs = null;
                        ++filesCount;
                        if (filesCount == files.Count)
                        {
                            this.Invoke(new Action(() =>
                            {
                                try
                                {
                                    var fb = Path.Combine(GetAssemblyPath(), "OnLineLogFileClient.Move.exe");
                                    Process.Start(fb,
                                        "-s OnLineLogFileClient.exe -sarg \"-ar 1 -lf 1\" -f " + updatePath + " -t " + GetAssemblyPath());
                                }
                                catch (Exception ex)
                                {
                                    this.InvMsg(ex.ToString());
                                }
                                Environment.Exit(0);
                            }));
                        }
                    }
                };
                foreach (var item in files)
                {
                    this.InvMsg(item);
                }

                foreach (var item in files)
                {
                    cmd.CommandType = OnLineLogFileComm.CommandType.UpdateClientFile;
                    cmd.Data = item;
                    client.Send(cmd);
                }

            });
        }
        void InvMsg(string msg)
        {
            this.Invoke(new Action(() =>
            {
                if (this.richTextBox1.TextLength > 200000)
                {
                    this.richTextBox1.Clear();
                }
                this.richTextBox1.AppendText(msg + Environment.NewLine);
                this.richTextBox1.ScrollToCaret();
                this.richTextBox1.Focus();
            }));
        }
        private static string GetAssemblyPath()
        {
            string l = System.Reflection.Assembly.GetEntryAssembly().Location;

            FileInfo fi = new FileInfo(l);
            Console.WriteLine("==========" + fi.DirectoryName);
            return fi.DirectoryName;
        }

    }
}
